package com.thb.pay.core.utils;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;

public class PermissionTreeBuilder {

    List<Node> nodes = new ArrayList<>();


    public PermissionTreeBuilder(List<Node> nodes) {
        super();
        this.nodes = nodes;
    }

    public static List<Node> buildListTree(List<Node> nodes) {
        PermissionTreeBuilder permissionTreeBuilder = new PermissionTreeBuilder(nodes);
        return permissionTreeBuilder.buildTree();
    }


    // 构建树形结构
    public List<Node> buildTree() {
        List<Node> treeNodes = new ArrayList<>();
        List<Node> rootNodes = getRootNodes();
        for (Node rootNode : rootNodes) {
            buildChildNodes(rootNode);
            treeNodes.add(rootNode);
        }
        return treeNodes;
    }

    // 递归子节点
    public void buildChildNodes(Node node) {
        List<Node> children = getChildNodes(node);
        if (!children.isEmpty()) {
            for (Node child : children) {
                buildChildNodes(child);
            }
            node.setData(children);
        }
    }

    // 获取父节点下所有的子节点
    public List<Node> getChildNodes(Node pnode) {
        List<Node> childNodes = new ArrayList<>();
        for (Node n : nodes) {
            if (pnode.getResourceId().equals(n.getParentId())) {
                childNodes.add(n);
            }
        }
        return childNodes;
    }

    // 判断是否为根节点
    public boolean rootNode(Node node) {
        boolean isRootNode = true;
        for (Node n : nodes) {
            if (node.getParentId() != null && node.getParentId().equals(n.getResourceId())) {
                isRootNode = false;
                break;
            }
        }
        return isRootNode;
    }

    // 获取集合中所有的根节点
    public List<Node> getRootNodes() {
        List<Node> rootNodes = new ArrayList<>();
        for (Node n : nodes) {
            if (rootNode(n)) {
                rootNodes.add(n);
            }
        }
        return rootNodes;
    }

    @Data
    public static class Node {
        private Long resourceId;
        private String title;
        private String value;
        private Boolean checked = false;
        private Boolean disabled = false;
        private Long parentId;
        private List<Node> data = new ArrayList<>();
    }
}